package com.xlh.security;

import com.google.common.collect.Lists;
import com.xlh.dto.user.ClassCourseDTO;
import com.xlh.dto.user.ClassDTO;
import com.xlh.service.course.CourseService;
import com.xlh.service.user.ClassService;
import com.xlh.virtualization.service.ContainerService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @author cheer
 */
@Component
public class PermissionValidator {

    @Autowired
    private UserInfoHolder userInfoHolder;

    @Autowired
    private CourseService courseService;

    @Autowired
    private ContainerService containerService;

    @Autowired
    private ClassService classService;

    /**
     * 检查当前学生是否结课
     *
     * @param courseId 课程id
     * @return
     */
    public boolean isStudentEndClass(Long courseId) {

        if (!userInfoHolder.isStudent()) return false;

        List<ClassCourseDTO> classCourseDTOS = classService.listClassCourse(Lists.newArrayList(courseId), true);
        if (CollectionUtils.isEmpty(classCourseDTOS)) return false;

        // 获取学生的班级id集合
        List<Long> studentClassIds = userInfoHolder.getStudentClassIds();
        if (CollectionUtils.isEmpty(studentClassIds)) return false;

        if (classCourseDTOS.stream()
                .filter(classCourseDTO -> studentClassIds.contains(classCourseDTO.getId()))
                .count() > 0) {
            return true;
        }

        return false;
    }

    /**
     * 检查当前教师是否教这个课程和这个班级
     *
     * @param courseId 课程
     * @param classId  班级id
     * @param endFlag  结课标识
     * @return
     */
    public boolean isTeaching(Long courseId, Long classId, Boolean endFlag) {
        if (!userInfoHolder.isTeacher()) return false;

        // 获取这个课程、当前教师教授的班级
        List<ClassDTO> classDTOS = classService.listClassCourse(
                courseId, userInfoHolder.getUserId(), null, endFlag, null);
        if (CollectionUtils.isEmpty(classDTOS)) return false;

        return classDTOS.stream().filter(classDTO -> Objects.equals(classDTO.getId(), classId)).count() > 0;
    }

    public boolean isCourseOwner(Long courseId) {
        List<Long> userIds = courseService.getCourseTeacherIds(courseId, null);
        return userIds.contains(userInfoHolder.getUserId());
    }

    public boolean isAdmin() {
        return userInfoHolder.isAdmin();
    }

    public boolean isTeacher() {
        return userInfoHolder.isTeacher();
    }

    public boolean isStudent() {
        return userInfoHolder.isStudent();
    }

    public boolean isAdminOrTeacher() {
        return userInfoHolder.isAdmin() || userInfoHolder.isTeacher();
    }

    public boolean isTeacherOrStudent() {
        return userInfoHolder.isTeacher() || userInfoHolder.isStudent();
    }
}
